package com.dlc.beijingrfid.activity;

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.dlc.beijingrfid.R;
import com.dlc.beijingrfid.adapter.AddHandworkAdapter;
import com.dlc.beijingrfid.base.BaseActivity;
import com.dlc.beijingrfid.net.bean.AddHandworkData;
import com.dlc.beijingrfid.net.bean.HotelBean;
import com.dlc.beijingrfid.net.bean.ProductListBean;
import com.dlc.beijingrfid.net.bean.SimpleBean;
import com.dlc.beijingrfid.net.protocol.OrderProto;
import com.dlc.beijingrfid.net.protocol.StockProto;
import com.dlc.commonlibrary.dialog.SureDialog;
import com.dlc.commonlibrary.utils.LogPlus;
import com.dlc.commonlibrary.utils.RecyclerViewUtil;
import com.dlc.commonlibrary.utils.TimeFormats;
import com.dlc.commonlibrary.utils.ToastUtil;
import com.dlc.commonlibrary.widget.CommonItemView;
import com.dlc.commonlibrary.widget.TitleBar;
import com.dlc.commonlibrary.widget.popup.CommonPopupList;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import java.util.ArrayList;
import java.util.List;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class AddHandworkActivity extends BaseActivity implements OnDateSetListener {
    @BindView(R.id.titleBar)
    TitleBar mTitleBar;
    @BindView(R.id.tv_hotel)
    TextView mTvHotel;
    @BindView(R.id.drop_hotel)
    FrameLayout mDropHotel;
    @BindView(R.id.item_hotel)
    CommonItemView mItemHotel;
    @BindView(R.id.tv_productName)
    TextView mTvProductName;
    @BindView(R.id.drop_product)
    FrameLayout mDropProduct;
    @BindView(R.id.item_name)
    CommonItemView mItemName;
    @BindView(R.id.num)
    EditText num;

    @BindView(R.id.mRecyclerView)
    RecyclerView mMRecyclerView;
    @BindView(R.id.get_time)
    CommonItemView get_time;

    private AddHandworkAdapter mAddHandworkAdapter ;

    private CommonPopupList mProductPopup;//产品名称
    List<ProductListBean.DataBean> productList;
    private Integer productId = null;

    private CommonPopupList mHotelPopup;//酒店
    List<HotelBean.DataBean> HotelList;
    private String HotelId = null;

    private List<AddHandworkData> mList = new ArrayList<>();
    private int type = 0;//打印
    private boolean isBold, isUnderLine;
    private int record;
    private String[] mStrings = new String[]{"CP437", "CP850", "CP860", "CP863", "CP865", "CP857", "CP737", "Windows-1252", "CP866", "CP852", "CP858", "CP874", "Windows-775", "CP855", "CP862", "CP864", "GB18030", "BIG5", "KSC5601", "utf-8"};
    private Handler mHandler = new Handler();

    TimePickerDialog mDialogYearMonthDay;
    @Override
    protected int getLayoutID() {
        return R.layout.activity_add_handwork;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        mTitleBar.leftImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        InitRecyclerView();
        isBold = false;
        isUnderLine = false;
        mDialogYearMonthDay = new TimePickerDialog.Builder()
            .setType(Type.ALL)
            .setCallBack(this)
            .build();
    }
    @OnClick({ R.id.drop_hotel, R.id.drop_product, R.id.btn_add_goods,
        R.id.btn_wash,R.id.btn_goods ,R.id.btn_print,R.id.get_time})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.drop_hotel:
                mHotelPopup.showAsDropDown(view);
                break;
            case R.id.drop_product:
                mProductPopup.showAsDropDown(view);
                break;
            case R.id.btn_add_goods:
                String product = (String) mTvProductName.getText();
                String nums = num.getText().toString();
                if (TextUtils.isEmpty(product)||TextUtils.isEmpty(nums)){
                    ToastUtil.show(AddHandworkActivity.this,"产品名称或者数量不能为空");
                    return;
                }
                AddHandworkData bean = new AddHandworkData(product,nums);
                mList.add(bean);
                mAddHandworkAdapter.setNewData(mList);
                type = 0;
                break;
            case R.id.btn_wash:
                String stime ="";
                stime= get_time.getContentText();
                if (TextUtils.isEmpty(stime)){
                    showOneToast("收单时间不能为空");
                    return;
                }
                SureDialog sureDialog =
                    new SureDialog(AddHandworkActivity.this, getString(R.string.submit_add1));
                sureDialog.setOnCallBackListener(new SureDialog.OnCallBack() {
                    @Override
                    public void sure() {
                        manual_record(1,get_time.getContentText());
                    }

                    @Override

                    public void cancle() {

                    }
                });

                break;
            case R.id.btn_goods:
                String stime1 ="";
                stime1= get_time.getContentText();
                if (TextUtils.isEmpty(stime1)){
                    showOneToast("收单时间不能为空");
                    return;
                }
                SureDialog sureDialog1 =
                    new SureDialog(AddHandworkActivity.this, getString(R.string.submit_add2));
                sureDialog1.setOnCallBackListener(new SureDialog.OnCallBack() {
                    @Override
                    public void sure() {
                        manual_record(2,get_time.getContentText());
                    }

                    @Override
                    public void cancle() {

                    }
                });
                break;
            case R.id.btn_print:
                // print();
                break;
            case R.id.get_time:
                mDialogYearMonthDay.show(getSupportFragmentManager(), "All");
                break;
        }
    }
    private void InitRecyclerView(){
        mAddHandworkAdapter = new AddHandworkAdapter();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        mMRecyclerView.setLayoutManager(linearLayoutManager);
        RecyclerViewUtil.setDefaultDivider(mMRecyclerView, linearLayoutManager);
        mMRecyclerView.setAdapter(mAddHandworkAdapter);
        mAddHandworkAdapter.setOnItemClickListener(new AddHandworkAdapter.OnItemClickListener() {
            @Override
            public void onClick(int position) {
                mList.remove(position);
                mAddHandworkAdapter.setNewData(mList);
            }
        });
        mHotelPopup = CommonPopupList.newBuilder(this)
            .setWidthEquals(mDropHotel)
            .setOnSelectItemListener(new CommonPopupList.OnSelectItemListener() {
                @Override
                public void onSelectItem(CommonPopupList popup, String item, int position) {
                    popup.dismiss();
                    // TODO: 2017/7/20
                    mTvHotel.setText(item);
                    if(HotelList != null) {
                        HotelId = HotelList.get(position).getId();
                    }

                }
            })
            .build();

        getHotelPopupListData();

        mProductPopup = CommonPopupList.newBuilder(this)
            .setWidthEquals(mDropProduct)
            .setOnSelectItemListener(new CommonPopupList.OnSelectItemListener() {
                @Override
                public void onSelectItem(CommonPopupList popup, String item, int position) {
                    popup.dismiss();
                    mTvProductName.setText(item);
                    productId = productList.get(position).getId();
                }
            })
            .build();
        initProductPopupList();
    }
    private void getHotelPopupListData() {
        OrderProto.get().getHotel().
            subscribeOn(Schedulers.io()).
            observeOn(AndroidSchedulers.mainThread()).
            subscribe(new Observer<HotelBean>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    LogPlus.e(e.getMessage());
                }

                @Override
                public void onNext(HotelBean hotelBean) {
                    if(hotelBean != null && hotelBean.getData() != null){
                        List<String> datas = new ArrayList<>();
                        HotelList = hotelBean.getData();
                        for(HotelBean.DataBean bean : hotelBean.getData()){
                            datas.add(bean.getTitle());
                        }
                        mHotelPopup.setData(datas);
                    }
                }
            });
    }

    /**
     * 初始化产品下拉
     */
    private void initProductPopupList() {
        StockProto.get()
            .goods2( "")
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<ProductListBean>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    ToastUtil.show(getActivity(), e.getMessage());
                }

                @Override
                public void onNext(ProductListBean bean) {
                    productList = bean.data;

                    if (productList != null) {
                        String[] productNames = new String[productList.size()];
                        for (int i = 0; i < productList.size(); i++) {
                            productNames[i] = productList.get(i).getName();
                        }
                        mProductPopup.setData(productNames);
                    }
                }
            });
    }

    private void manual_record(final int  type,String receivetime){

        StringBuilder sbtitle = new StringBuilder();
        StringBuilder sbnum = new StringBuilder();
        if (mList.size()==0){
            showOneToast("产品不能为空");
            return;
        }
        for(int i = 0;i < mList.size();i++){
            sbtitle.append(mList.get(i).goods_name+",");
            sbnum.append(mList.get(i).nums+",");
        }
        String title = sbtitle.substring(0,sbtitle.length()-1);
        String nums = sbnum.substring(0,sbnum.length()-1);
        showWaitingDialog("请稍等",false);
        OrderProto.get().manual_record(HotelId,title,nums,type+"",receivetime)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<SimpleBean>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    showToast(e.getMessage());
                    dismissWaitingDialog();
                }

                @Override
                public void onNext(SimpleBean dataBean) {
                    dismissWaitingDialog();
                    showOneToast(dataBean.msg);
                    AddHandworkActivity.this.type = type;
                    //print();
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {

                            mAddHandworkAdapter.setNewData(null);
                            mList.clear();
                        }
                    },1000);

                }
            });
    }

    //private void print(){
    //    String string = "";
    //
    //     if (type == 1) {
    //        string = "          " + getString(R.string.songxi_hint) + "\r\n"  + "\r\n";
    //    } else  if (type == 2){
    //        string = "          " + getString(R.string.songhuo_hint) + "\r\n"  + "\r\n";
    //    }else {
    //         ToastUtil.show(AddHandworkActivity.this,"請先提交");
    //         return;
    //     }
    //    string = string + getString(R.string.client) + "：" +  mTvHotel.getText() + "\r\n";
    //    SimpleDateFormat formatter   =   new   SimpleDateFormat   ("yyyy-MM-dd HH:mm");
    //    Date curDate =  new Date(System.currentTimeMillis());
    //    String   str   =   formatter.format(curDate);
    //    string = string + getString(R.string.date) + "：" + str+ "\r\n";
    //
    //    for (int i = 0; i < mList.size(); i++) {
    //        string = string + "\r\n" + (getString(R.string.product_name) + ": " + mList.get(i).goods_name + "\r\n"
    //            + getString(R.string.amount) + ": " + mList.get(i).nums);
    //        string = string + "\r\n";
    //        string = string + "-------------------------";
    //    }
    //    string = string + "\r\n";
    //    string = string + getString(R.string.signature) + "：" + "\r\n" + "\r\n" + "\r\n";
    //    byte[] rv = null;
    //    //rv = BytesUtil.getBytesFromHexString();
    //    //AidlUtil.getInstance().sendRawData(BytesUtil.getBytesFromHexString(text));
    //    //sendData(rv);
    //    sendData(string);
    //}
    //
    //private void sendData(final String content) {
    //    if (baseApp.isAidl()) {
    //        AidlUtil.getInstance().printText(content, 30, isBold, isUnderLine);
    //    } else {
    //        printByBluTooth(content);
    //    }
    //}
    //
    //private void printByBluTooth(String content) {
    //    try {
    //        if (isBold) {
    //            BluetoothUtil.sendData(ESCUtil.boldOn());
    //        } else {
    //            BluetoothUtil.sendData(ESCUtil.boldOff());
    //        }
    //
    //        if (isUnderLine) {
    //            BluetoothUtil.sendData(ESCUtil.underlineWithOneDotWidthOn());
    //        } else {
    //            BluetoothUtil.sendData(ESCUtil.underlineOff());
    //        }
    //
    //        if (record < 17) {
    //            BluetoothUtil.sendData(ESCUtil.singleByte());
    //            BluetoothUtil.sendData(ESCUtil.setCodeSystemSingle(codeParse(record)));
    //        } else {
    //            BluetoothUtil.sendData(ESCUtil.singleByteOff());
    //            BluetoothUtil.sendData(ESCUtil.setCodeSystem(codeParse(record)));
    //        }
    //
    //        BluetoothUtil.sendData(content.getBytes(mStrings[record]));
    //        BluetoothUtil.sendData(ESCUtil.nextLine(3));
    //    } catch (IOException e) {
    //        e.printStackTrace();
    //    }
    //}

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //BluetoothUtil.disconnectBlueTooth(this);
    }

    private byte codeParse(int value) {
        byte res = 0x00;
        switch (value) {
            case 0:
                res = 0x00;
                break;
            case 1:
            case 2:
            case 3:
            case 4:
                res = (byte) (value + 1);
                break;
            case 5:
            case 6:
            case 7:
            case 8:
            case 9:
            case 10:
            case 11:
                res = (byte) (value + 8);
                break;
            case 12:
                res = 21;
                break;
            case 13:
                res = 33;
                break;
            case 14:
                res = 34;
                break;
            case 15:
                res = 36;
                break;
            case 16:
                res = 37;
                break;
            case 17:
            case 18:
            case 19:
                res = (byte) (value - 17);
                break;
            case 20:
                res = (byte) 0xff;
                break;
        }
        return (byte) res;
    }

    @Override
    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
        get_time.setContent(TimeFormats.formatDateTimeSecend(timePickerView.getCurrentMillSeconds()));
    }
}
